<template>
  <el-dialog
    v-model="dialogVisible"
    class="association-role-dialog"
    title="关联角色"
    width="800px"
    draggable
    @closed="closeDialog"
  >
    <el-transfer
      class="role-transfer"
      v-model="associationRoles"
      filterable
      :titles="['角色列表', '当前角色']"
      :filter-method="filterMethod"
      filter-placeholder="请输入关键字"
      :data="roulOptions"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveUserRoles">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onBeforeMount, toRef, watch } from 'vue'
import {
  ElMessage,
  ElMessageBox,
  type TransferPropsAlias,
} from 'element-plus'
import { restHelperInstance } from '@/composables/useGeoHelper'
import type { ISecurity } from 'geoserver-helper/interface'
//角色列表
const roulOptions = ref<TransferPropsAlias[]>([])
//关联的角色
const associationRoles = ref<string[]>([])
//初始情况下关联的角色
const corignAssociationRoles = ref<string[]>([])
interface propsType {
  visible: boolean
  userInfo?: ISecurity.UserInfo
}
const props = withDefaults(defineProps<propsType>(), {
  visible: false,
})
const dialogVisible = toRef(props, 'visible')

// 过滤方法
const filterMethod = (query: string, item: TransferPropsAlias) => {
  return item.label!.toLowerCase().includes(query.toLowerCase())
}

interface emitInterface {
  (e: 'update:visible', v: boolean): void
}
const emit = defineEmits<emitInterface>()

const closeDialog = () => {
  emit('update:visible', false)
}
/**
 * @description: 保存用户角色
 * @return {*}
 */
const saveUserRoles = () => {
  ElMessageBox.confirm('确认保存当前关联角色么?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const addRoles = associationRoles.value.filter((item) => {
      return !corignAssociationRoles.value.includes(item)
    })
    const removeRoles = corignAssociationRoles.value.filter((item) => {
      return !associationRoles.value.includes(item)
    })
    const promiseArray: Promise<string>[] = []
    addRoles.forEach((item) => {
      promiseArray.push(restHelperInstance.addUserRole(props.userInfo!.userName, item))
    })
    removeRoles.forEach((item) => {
      promiseArray.push(restHelperInstance.deleteUserRole(props.userInfo!.userName, item))
    })
    Promise.all(promiseArray)
      .then(() => {
        ElMessage({
          type: 'success',
          message: '保存成功',
        })
        closeDialog()
      })
      .catch(() => {
        ElMessage({
          type: 'error',
          message: '保存失败!',
        })
      })
  })
}
/**
 * @description: 初始化角色穿梭框
 * @return {*}
 */
const initRoleTransfer = () => {
  restHelperInstance
    .getRoles()
    .then((res) => {
      if (res.roles) {
        roulOptions.value = res.roles.map((item) => {
          return {
            key: item,
            label: item,
          }
        })
      } else {
        roulOptions.value = []
        ElMessage({
          type: 'error',
          message: '获取角色列表失败!',
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'error',
        message: '获取角色列表失败!',
      })
    })
  if (props.userInfo) {
    restHelperInstance.getUserRoles(props.userInfo!.userName).then((res) => {
      if (res.roles) {
        associationRoles.value = res.roles.map((item) => {
          return item
        })
        corignAssociationRoles.value = res.roles.map((item) => {
          return item
        })
      } else {
        associationRoles.value = []
        corignAssociationRoles.value = []
        ElMessage({
          type: 'error',
          message: '获取用户角色列表失败!',
        })
      }
    })
  }
}

onBeforeMount(() => {})
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      initRoleTransfer()
    }
  },
)

defineExpose({})
</script>
<style lang="scss">
.association-role-dialog {
  .el-dialog__body {
    padding: 20px;
    .role-transfer {
      display: flex;
      align-items: center;
      justify-content: space-around;
      width: 100%;
    }
  }
  .el-dialog__footer {
    padding: 20px;
    text-align: center;
  }
}
</style>
